package com.zhoufy.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-04-29.
 *
 * @author chouFy
 */
public class GetChildData implements Watcher {

    public List<String> children;


    private static ZooKeeper zooKeeper;


    /**
     * 回调方法 处理服务器端的watcher通知
     *
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 接触主程序countDownLatch 等待堵塞
            System.out.println("process method action");
        }

        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            System.out.println("节点发生变化");
            try {
                 children = zooKeeper.getChildren("/zhoufy-persistent", true);
                for (String child : children) {
                    System.out.println("获取到child ：" + child);
                }
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 创建节点方法
     */
    public static void getChildren() throws Exception {

        zooKeeper = new ZooKeeper("localhost:2181", 5000, new GetChildData());

        System.out.println("111" + zooKeeper.getState());

        List<String> children = zooKeeper.getChildren("/zhoufy-persistent", true);
        for (String child : children) {
            System.out.println("获取到child ：" + child);
        }

    }


    public static void main(String[] args) throws Exception {


        GetChildData.getChildren();

        try {
            // 线程暂停一会
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
